from django.db import models

# Create your models here.

class BookManager(models.Manager):
    def title_count(self,keyword):
        return self.filter(title__icontains=keyword).count()

class Publisher(models.Model):
    name = models.CharField(max_length = 30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

    def __str__(self):
        return self.name
    
    class Meta:
        ordering =['-name']

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(blank=True,verbose_name='e-mail')

    def __str__(self):
        return '%s %s' % (self.first_name,self.last_name)
    
    class Meta:
        ordering = ['id']

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
    publication_date = models.DateField(blank=True, null=True)
    num_pages = models.IntegerField(blank=True,null=True)
    objects = BookManager()

    def __str__(self):
        return self.title

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()

    def baby_boomer_status(self):
        import datetime
        if self.birth_date < datetime.date(1954,8,1):
            return "Pre-boomer"
        elif self.birth_date <datetime.date(1965,1,1):
            return "Baby boomer"
        else:
            return "Post-boomer"
    
    def _get_full_name(self):
        return "%s %s" % (self.first_name,self.last_name)
    
    def save(self,*args,**kwargs):
        if self.first_name == "mhye":
            self.first_name = "Mhye"
        super(Person,self).save(*args,**kwargs)
    full_name = property(_get_full_name)